package com.yjd.comm.asynmsg;

import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.asynmsg.model.TaskMsgModel;
import com.yjd.comm.asynmsg.model.TaskMsgProcessDataModel;
import com.yjd.comm.asynmsg.service.ITaskMsgProcessDataService;
import com.yjd.comm.asynmsg.service.ITaskMsgService;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.util.FrameUtil;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <b>description</b>：消息默认处理器，其他消息处理器继承该类，该类已经做了避免消息重复处理的操作 <br>
 * <b>time</b>：2015-1-23下午5:09:04 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public abstract class MsgProcessorDefaultServiceImpl implements
		IMsgProcessorService {

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	protected ITaskMsgProcessDataService taskMsgProcessDataService;
	
	@Resource
	protected ITaskMsgService taskMsgService;

	@SuppressWarnings("rawtypes")
	@Override
	public void process(TaskMsgModel taskMsgModel) throws Exception {
		Map context = new HashMap();
		if (this.onBefore(taskMsgModel, context)) {
			this.onProcess(taskMsgModel, context);
		}
		this.onAfter(taskMsgModel, context);
	}

	/**
	 * 处理之前调用的方法，返回true表示需要处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	protected boolean onBefore(TaskMsgModel taskMsgModel, Map context)
			throws Exception {
		// 此处需要验证消息是否处理过，如果没有处理过，将mp入库标志消息已经处理
		String id = taskMsgModel.getId() + "_" + this.getClass().getName();
		if (this.taskMsgProcessDataService.getModelById(id, DbWREnums.WRITE) != null) {
			return false;
		} else {
			TaskMsgProcessDataModel mp = new TaskMsgProcessDataModel();
			mp.setId(id);
			mp.setTask_msg_id(taskMsgModel.getId());
			mp.setType(this.getClass().getName());
			mp.setCreate_time(FrameUtil.getTime(null));
			this.taskMsgProcessDataService.insert(mp);
			return true;
		}
	}

	/**
	 * 处理消息的方法
	 * 
	 * @param taskMsgModel
	 *            消息体
	 * @param context
	 *            上线文
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	protected abstract void onProcess(TaskMsgModel taskMsgModel, Map context)
			throws Exception;

	/**
	 * 消息处理完毕调用的方法
	 * 
	 * @param taskMsgModel
	 *            消息
	 * @param context
	 *            上下文
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	protected void onAfter(TaskMsgModel taskMsgModel, Map context)
			throws Exception {
	}
}
